package com.ruoyi.framework.config;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.ServletUtils;

import java.net.InetAddress;

/**
 * 服务相关配置
 * 
 * @author ruoyi
 */
@Component
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {

    private int serverPort;
    private String contextPath;

    public String getUrl() {
        InetAddress address = null;
        try {
            // InetAddress.getLoopbackAddress()
            address = InetAddress.getLoopbackAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "http://" + address.getHostAddress() +":" + this.serverPort + this.contextPath;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();

        this.contextPath = event.getApplicationContext().getEnvironment().getProperty("server.servlet.context-path");

    }

    public static String getDomain(HttpServletRequest request)
    {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

    public String getContextPath() {
        return contextPath;
    }
}
